package com.lifeverse.service;

import com.lifeverse.entity.AuditLog;
import com.lifeverse.entity.enums.AuditAction;
import com.lifeverse.entity.enums.AuditResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 合规性报告生成服务
 * 生成各种合规性报告，满足审计和监管要求
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional(readOnly = true)
public class ComplianceReportService {
    
    private final AuditLogService auditLogService;
    private final SystemBehaviorTracker systemBehaviorTracker;
    
    /**
     * 合规性报告类型
     */
    public enum ComplianceReportType {
        GDPR_COMPLIANCE("GDPR合规报告"),
        SOX_COMPLIANCE("SOX合规报告"),
        ISO27001_COMPLIANCE("ISO27001合规报告"),
        SECURITY_AUDIT("安全审计报告"),
        ACCESS_CONTROL("访问控制报告"),
        DATA_PROTECTION("数据保护报告"),
        INCIDENT_RESPONSE("事件响应报告"),
        USER_ACTIVITY("用户活动报告"),
        SYSTEM_INTEGRITY("系统完整性报告"),
        CHANGE_MANAGEMENT("变更管理报告");
        
        private final String description;
        
        ComplianceReportType(String description) {
            this.description = description;
        }
        
        public String getDescription() {
            return description;
        }
    }
    
    /**
     * 合规性报告结果
     */
    public static class ComplianceReport {
        private ComplianceReportType reportType;
        private String title;
        private LocalDateTime generatedAt;
        private LocalDateTime reportPeriodStart;
        private LocalDateTime reportPeriodEnd;
        private String executiveSummary;
        private List<ComplianceSection> sections;
        private Map<String, Object> statistics;
        private List<ComplianceFinding> findings;
        private List<String> recommendations;
        private String complianceStatus;
        private Double complianceScore;
        
        public ComplianceReport(ComplianceReportType reportType) {
            this.reportType = reportType;
            this.title = reportType.getDescription();
            this.generatedAt = LocalDateTime.now();
            this.sections = new ArrayList<>();
            this.statistics = new HashMap<>();
            this.findings = new ArrayList<>();
            this.recommendations = new ArrayList<>();
        }
        
        // Getters and Setters
        public ComplianceReportType getReportType() { return reportType; }
        public void setReportType(ComplianceReportType reportType) { this.reportType = reportType; }
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public LocalDateTime getGeneratedAt() { return generatedAt; }
        public void setGeneratedAt(LocalDateTime generatedAt) { this.generatedAt = generatedAt; }
        
        public LocalDateTime getReportPeriodStart() { return reportPeriodStart; }
        public void setReportPeriodStart(LocalDateTime reportPeriodStart) { this.reportPeriodStart = reportPeriodStart; }
        
        public LocalDateTime getReportPeriodEnd() { return reportPeriodEnd; }
        public void setReportPeriodEnd(LocalDateTime reportPeriodEnd) { this.reportPeriodEnd = reportPeriodEnd; }
        
        public String getExecutiveSummary() { return executiveSummary; }
        public void setExecutiveSummary(String executiveSummary) { this.executiveSummary = executiveSummary; }
        
        public List<ComplianceSection> getSections() { return sections; }
        public void setSections(List<ComplianceSection> sections) { this.sections = sections; }
        
        public Map<String, Object> getStatistics() { return statistics; }
        public void setStatistics(Map<String, Object> statistics) { this.statistics = statistics; }
        
        public List<ComplianceFinding> getFindings() { return findings; }
        public void setFindings(List<ComplianceFinding> findings) { this.findings = findings; }
        
        public List<String> getRecommendations() { return recommendations; }
        public void setRecommendations(List<String> recommendations) { this.recommendations = recommendations; }
        
        public String getComplianceStatus() { return complianceStatus; }
        public void setComplianceStatus(String complianceStatus) { this.complianceStatus = complianceStatus; }
        
        public Double getComplianceScore() { return complianceScore; }
        public void setComplianceScore(Double complianceScore) { this.complianceScore = complianceScore; }
    }
    
    /**
     * 合规性报告章节
     */
    public static class ComplianceSection {
        private String sectionTitle;
        private String content;
        private Map<String, Object> data;
        private String status;
        
        public ComplianceSection(String sectionTitle, String content) {
            this.sectionTitle = sectionTitle;
            this.content = content;
            this.data = new HashMap<>();
        }
        
        // Getters and Setters
        public String getSectionTitle() { return sectionTitle; }
        public void setSectionTitle(String sectionTitle) { this.sectionTitle = sectionTitle; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public Map<String, Object> getData() { return data; }
        public void setData(Map<String, Object> data) { this.data = data; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
    }
    
    /**
     * 合规性发现
     */
    public static class ComplianceFinding {
        private String findingType;
        private String severity;
        private String description;
        private String evidence;
        private String recommendation;
        private LocalDateTime discoveredAt;
        
        public ComplianceFinding(String findingType, String severity, String description) {
            this.findingType = findingType;
            this.severity = severity;
            this.description = description;
            this.discoveredAt = LocalDateTime.now();
        }
        
        // Getters and Setters
        public String getFindingType() { return findingType; }
        public void setFindingType(String findingType) { this.findingType = findingType; }
        
        public String getSeverity() { return severity; }
        public void setSeverity(String severity) { this.severity = severity; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public String getEvidence() { return evidence; }
        public void setEvidence(String evidence) { this.evidence = evidence; }
        
        public String getRecommendation() { return recommendation; }
        public void setRecommendation(String recommendation) { this.recommendation = recommendation; }
        
        public LocalDateTime getDiscoveredAt() { return discoveredAt; }
        public void setDiscoveredAt(LocalDateTime discoveredAt) { this.discoveredAt = discoveredAt; }
    }
    
    /**
     * 生成合规性报告
     */
    public ComplianceReport generateComplianceReport(ComplianceReportType reportType, 
                                                   LocalDateTime startTime, 
                                                   LocalDateTime endTime) {
        ComplianceReport report = new ComplianceReport(reportType);
        report.setReportPeriodStart(startTime);
        report.setReportPeriodEnd(endTime);
        
        try {
            switch (reportType) {
                case GDPR_COMPLIANCE:
                    return generateGDPRComplianceReport(report, startTime, endTime);
                case SOX_COMPLIANCE:
                    return generateSOXComplianceReport(report, startTime, endTime);
                case ISO27001_COMPLIANCE:
                    return generateISO27001ComplianceReport(report, startTime, endTime);
                case SECURITY_AUDIT:
                    return generateSecurityAuditReport(report, startTime, endTime);
                case ACCESS_CONTROL:
                    return generateAccessControlReport(report, startTime, endTime);
                case DATA_PROTECTION:
                    return generateDataProtectionReport(report, startTime, endTime);
                case INCIDENT_RESPONSE:
                    return generateIncidentResponseReport(report, startTime, endTime);
                case USER_ACTIVITY:
                    return generateUserActivityReport(report, startTime, endTime);
                case SYSTEM_INTEGRITY:
                    return generateSystemIntegrityReport(report, startTime, endTime);
                case CHANGE_MANAGEMENT:
                    return generateChangeManagementReport(report, startTime, endTime);
                default:
                    throw new IllegalArgumentException("不支持的报告类型: " + reportType);
            }
        } catch (Exception e) {
            log.error("生成合规性报告失败: reportType={}", reportType, e);
            report.setComplianceStatus("ERROR");
            report.setExecutiveSummary("报告生成失败: " + e.getMessage());
            return report;
        }
    }
    
    /**
     * 生成GDPR合规报告
     */
    private ComplianceReport generateGDPRComplianceReport(ComplianceReport report, 
                                                        LocalDateTime startTime, 
                                                        LocalDateTime endTime) {
        report.setExecutiveSummary("GDPR（通用数据保护条例）合规性评估报告");
        
        // 数据访问控制
        ComplianceSection accessControlSection = new ComplianceSection(
                "数据访问控制", 
                "评估个人数据访问控制措施的有效性"
        );
        
        // 统计数据访问操作
        Long dataAccessOperations = auditLogService.countActionOperations(
                AuditAction.DATA_EXPORT, startTime, endTime);
        accessControlSection.getData().put("dataAccessOperations", dataAccessOperations);
        
        // 检查未授权访问
        List<AuditLog> unauthorizedAccess = auditLogService.findByMultipleConditions(
                null, AuditAction.API_UNAUTHORIZED, null, null, 
                startTime, endTime, null, 
                org.springframework.data.domain.Pageable.unpaged()
        ).getContent();
        
        if (!unauthorizedAccess.isEmpty()) {
            ComplianceFinding finding = new ComplianceFinding(
                    "UNAUTHORIZED_ACCESS", 
                    "HIGH", 
                    "检测到 " + unauthorizedAccess.size() + " 次未授权数据访问尝试"
            );
            finding.setRecommendation("加强访问控制措施，实施多因素认证");
            report.getFindings().add(finding);
        }
        
        accessControlSection.setStatus(unauthorizedAccess.isEmpty() ? "COMPLIANT" : "NON_COMPLIANT");
        report.getSections().add(accessControlSection);
        
        // 数据删除权利
        ComplianceSection dataDeletionSection = new ComplianceSection(
                "数据删除权利", 
                "评估数据主体删除权利的实施情况"
        );
        
        Long dataDeletionOperations = auditLogService.countActionOperations(
                AuditAction.DATA_PURGE, startTime, endTime);
        dataDeletionSection.getData().put("dataDeletionOperations", dataDeletionOperations);
        dataDeletionSection.setStatus("COMPLIANT");
        report.getSections().add(dataDeletionSection);
        
        // 计算合规性评分
        double complianceScore = calculateGDPRComplianceScore(report);
        report.setComplianceScore(complianceScore);
        report.setComplianceStatus(complianceScore >= 0.8 ? "COMPLIANT" : "NON_COMPLIANT");
        
        // 添加建议
        if (complianceScore < 0.8) {
            report.getRecommendations().add("加强数据访问控制措施");
            report.getRecommendations().add("实施数据最小化原则");
            report.getRecommendations().add("定期进行数据保护影响评估");
        }
        
        return report;
    }
    
    /**
     * 生成SOX合规报告
     */
    private ComplianceReport generateSOXComplianceReport(ComplianceReport report, 
                                                       LocalDateTime startTime, 
                                                       LocalDateTime endTime) {
        report.setExecutiveSummary("SOX（萨班斯-奥克斯利法案）合规性评估报告");
        
        // 内部控制
        ComplianceSection internalControlSection = new ComplianceSection(
                "内部控制", 
                "评估财务报告相关的内部控制有效性"
        );
        
        // 检查系统配置变更
        Long configChanges = auditLogService.countActionOperations(
                AuditAction.SYSTEM_CONFIG_UPDATE, startTime, endTime);
        internalControlSection.getData().put("configurationChanges", configChanges);
        
        // 检查未经授权的变更
        List<AuditLog> unauthorizedChanges = auditLogService.findByMultipleConditions(
                null, AuditAction.SYSTEM_CONFIG_UPDATE, AuditResult.DENIED, null,
                startTime, endTime, null,
                org.springframework.data.domain.Pageable.unpaged()
        ).getContent();
        
        if (!unauthorizedChanges.isEmpty()) {
            ComplianceFinding finding = new ComplianceFinding(
                    "UNAUTHORIZED_CHANGES", 
                    "HIGH", 
                    "检测到 " + unauthorizedChanges.size() + " 次未经授权的系统配置变更"
            );
            finding.setRecommendation("实施变更管理流程，要求所有配置变更都需要审批");
            report.getFindings().add(finding);
        }
        
        internalControlSection.setStatus(unauthorizedChanges.isEmpty() ? "COMPLIANT" : "NON_COMPLIANT");
        report.getSections().add(internalControlSection);
        
        // 计算合规性评分
        double complianceScore = calculateSOXComplianceScore(report);
        report.setComplianceScore(complianceScore);
        report.setComplianceStatus(complianceScore >= 0.8 ? "COMPLIANT" : "NON_COMPLIANT");
        
        return report;
    }
    
    /**
     * 生成ISO27001合规报告
     */
    private ComplianceReport generateISO27001ComplianceReport(ComplianceReport report, 
                                                            LocalDateTime startTime, 
                                                            LocalDateTime endTime) {
        report.setExecutiveSummary("ISO27001信息安全管理体系合规性评估报告");
        
        // 访问控制
        ComplianceSection accessControlSection = new ComplianceSection(
                "访问控制", 
                "评估信息系统访问控制措施"
        );
        
        // 统计访问控制相关操作
        Long accessOperations = auditLogService.countActionOperations(
                AuditAction.API_ACCESS, startTime, endTime);
        accessControlSection.getData().put("accessOperations", accessOperations);
        
        report.getSections().add(accessControlSection);
        
        // 计算合规性评分
        double complianceScore = 0.85; // 简化计算
        report.setComplianceScore(complianceScore);
        report.setComplianceStatus("COMPLIANT");
        
        return report;
    }
    
    /**
     * 生成安全审计报告
     */
    private ComplianceReport generateSecurityAuditReport(ComplianceReport report, 
                                                       LocalDateTime startTime, 
                                                       LocalDateTime endTime) {
        report.setExecutiveSummary("系统安全审计报告");
        
        // 获取行为分析报告
        Map<String, Object> behaviorReport = systemBehaviorTracker.generateBehaviorReport(startTime, endTime);
        
        // 安全事件统计
        ComplianceSection securityEventsSection = new ComplianceSection(
                "安全事件", 
                "系统安全事件统计和分析"
        );
        
        securityEventsSection.getData().putAll(behaviorReport);
        report.getSections().add(securityEventsSection);
        
        // 异常检测结果
        @SuppressWarnings("unchecked")
        List<SystemBehaviorTracker.AnomalyDetectionResult> anomalies = 
                (List<SystemBehaviorTracker.AnomalyDetectionResult>) behaviorReport.get("anomalies");
        
        if (anomalies != null && !anomalies.isEmpty()) {
            for (SystemBehaviorTracker.AnomalyDetectionResult anomaly : anomalies) {
                ComplianceFinding finding = new ComplianceFinding(
                        anomaly.getAnomalyType(),
                        anomaly.getSeverity() > 0.8 ? "HIGH" : anomaly.getSeverity() > 0.5 ? "MEDIUM" : "LOW",
                        anomaly.getDescription()
                );
                report.getFindings().add(finding);
            }
        }
        
        // 计算安全评分
        Double overallRiskScore = (Double) behaviorReport.get("overallRiskScore");
        double securityScore = 1.0 - (overallRiskScore != null ? overallRiskScore : 0.0);
        report.setComplianceScore(securityScore);
        report.setComplianceStatus(securityScore >= 0.7 ? "SECURE" : "AT_RISK");
        
        return report;
    }
    
    /**
     * 生成访问控制报告
     */
    private ComplianceReport generateAccessControlReport(ComplianceReport report, 
                                                       LocalDateTime startTime, 
                                                       LocalDateTime endTime) {
        report.setExecutiveSummary("系统访问控制评估报告");
        
        // 认证统计
        ComplianceSection authenticationSection = new ComplianceSection(
                "用户认证", 
                "用户认证活动统计"
        );
        
        Long loginAttempts = auditLogService.countActionOperations(AuditAction.LOGIN, startTime, endTime);
        Long failedLogins = auditLogService.countActionOperations(AuditAction.LOGIN_FAILED, startTime, endTime);
        
        authenticationSection.getData().put("loginAttempts", loginAttempts);
        authenticationSection.getData().put("failedLogins", failedLogins);
        
        double successRate = loginAttempts > 0 ? 1.0 - (double) failedLogins / (loginAttempts + failedLogins) : 1.0;
        authenticationSection.getData().put("successRate", successRate);
        
        report.getSections().add(authenticationSection);
        
        report.setComplianceScore(successRate);
        report.setComplianceStatus(successRate >= 0.9 ? "EXCELLENT" : successRate >= 0.8 ? "GOOD" : "NEEDS_IMPROVEMENT");
        
        return report;
    }
    
    /**
     * 生成数据保护报告
     */
    private ComplianceReport generateDataProtectionReport(ComplianceReport report, 
                                                        LocalDateTime startTime, 
                                                        LocalDateTime endTime) {
        report.setExecutiveSummary("数据保护措施评估报告");
        
        // 数据操作统计
        ComplianceSection dataOperationsSection = new ComplianceSection(
                "数据操作", 
                "数据相关操作统计"
        );
        
        Long dataExports = auditLogService.countActionOperations(AuditAction.DATA_EXPORT, startTime, endTime);
        Long dataImports = auditLogService.countActionOperations(AuditAction.DATA_IMPORT, startTime, endTime);
        Long dataBackups = auditLogService.countActionOperations(AuditAction.DATA_BACKUP, startTime, endTime);
        
        dataOperationsSection.getData().put("dataExports", dataExports);
        dataOperationsSection.getData().put("dataImports", dataImports);
        dataOperationsSection.getData().put("dataBackups", dataBackups);
        
        report.getSections().add(dataOperationsSection);
        
        report.setComplianceScore(0.9); // 简化评分
        report.setComplianceStatus("COMPLIANT");
        
        return report;
    }
    
    /**
     * 生成事件响应报告
     */
    private ComplianceReport generateIncidentResponseReport(ComplianceReport report, 
                                                          LocalDateTime startTime, 
                                                          LocalDateTime endTime) {
        report.setExecutiveSummary("安全事件响应评估报告");
        
        // 安全事件统计
        ComplianceSection incidentsSection = new ComplianceSection(
                "安全事件", 
                "安全事件处理统计"
        );
        
        Long securityIncidents = auditLogService.countActionOperations(AuditAction.SECURITY_INCIDENT, startTime, endTime);
        Long securityAlerts = auditLogService.countActionOperations(AuditAction.SECURITY_ALERT, startTime, endTime);
        
        incidentsSection.getData().put("securityIncidents", securityIncidents);
        incidentsSection.getData().put("securityAlerts", securityAlerts);
        
        report.getSections().add(incidentsSection);
        
        report.setComplianceScore(securityIncidents == 0 ? 1.0 : 0.7);
        report.setComplianceStatus(securityIncidents == 0 ? "NO_INCIDENTS" : "INCIDENTS_DETECTED");
        
        return report;
    }
    
    /**
     * 生成用户活动报告
     */
    private ComplianceReport generateUserActivityReport(ComplianceReport report, 
                                                      LocalDateTime startTime, 
                                                      LocalDateTime endTime) {
        report.setExecutiveSummary("用户活动监控报告");
        
        // 用户活动统计
        ComplianceSection userActivitySection = new ComplianceSection(
                "用户活动", 
                "用户操作活动统计"
        );
        
        List<Object[]> actionStats = auditLogService.getActionStatistics(startTime, endTime);
        userActivitySection.getData().put("actionStatistics", actionStats);
        
        report.getSections().add(userActivitySection);
        
        report.setComplianceScore(0.85);
        report.setComplianceStatus("NORMAL");
        
        return report;
    }
    
    /**
     * 生成系统完整性报告
     */
    private ComplianceReport generateSystemIntegrityReport(ComplianceReport report, 
                                                         LocalDateTime startTime, 
                                                         LocalDateTime endTime) {
        report.setExecutiveSummary("系统完整性评估报告");
        
        // 系统操作统计
        ComplianceSection systemOpsSection = new ComplianceSection(
                "系统操作", 
                "系统级操作统计"
        );
        
        Long systemConfigs = auditLogService.countActionOperations(AuditAction.SYSTEM_CONFIG_UPDATE, startTime, endTime);
        Long systemBackups = auditLogService.countActionOperations(AuditAction.SYSTEM_BACKUP, startTime, endTime);
        
        systemOpsSection.getData().put("configurationChanges", systemConfigs);
        systemOpsSection.getData().put("systemBackups", systemBackups);
        
        report.getSections().add(systemOpsSection);
        
        report.setComplianceScore(0.9);
        report.setComplianceStatus("INTACT");
        
        return report;
    }
    
    /**
     * 生成变更管理报告
     */
    private ComplianceReport generateChangeManagementReport(ComplianceReport report, 
                                                          LocalDateTime startTime, 
                                                          LocalDateTime endTime) {
        report.setExecutiveSummary("系统变更管理评估报告");
        
        // 变更统计
        ComplianceSection changesSection = new ComplianceSection(
                "系统变更", 
                "系统变更活动统计"
        );
        
        Long configChanges = auditLogService.countActionOperations(AuditAction.SYSTEM_CONFIG_UPDATE, startTime, endTime);
        Long userChanges = auditLogService.countActionOperations(AuditAction.USER_UPDATE, startTime, endTime);
        
        changesSection.getData().put("configurationChanges", configChanges);
        changesSection.getData().put("userChanges", userChanges);
        
        report.getSections().add(changesSection);
        
        report.setComplianceScore(0.88);
        report.setComplianceStatus("CONTROLLED");
        
        return report;
    }
    
    /**
     * 计算GDPR合规性评分
     */
    private double calculateGDPRComplianceScore(ComplianceReport report) {
        double score = 1.0;
        
        // 根据发现的问题扣分
        for (ComplianceFinding finding : report.getFindings()) {
            switch (finding.getSeverity()) {
                case "HIGH":
                    score -= 0.3;
                    break;
                case "MEDIUM":
                    score -= 0.2;
                    break;
                case "LOW":
                    score -= 0.1;
                    break;
            }
        }
        
        return Math.max(0.0, score);
    }
    
    /**
     * 计算SOX合规性评分
     */
    private double calculateSOXComplianceScore(ComplianceReport report) {
        double score = 1.0;
        
        // 根据发现的问题扣分
        for (ComplianceFinding finding : report.getFindings()) {
            switch (finding.getSeverity()) {
                case "HIGH":
                    score -= 0.4;
                    break;
                case "MEDIUM":
                    score -= 0.2;
                    break;
                case "LOW":
                    score -= 0.1;
                    break;
            }
        }
        
        return Math.max(0.0, score);
    }
    
    /**
     * 导出报告为文本格式
     */
    public String exportReportAsText(ComplianceReport report) {
        StringBuilder sb = new StringBuilder();
        
        sb.append("=".repeat(80)).append("\n");
        sb.append(report.getTitle()).append("\n");
        sb.append("=".repeat(80)).append("\n\n");
        
        sb.append("报告生成时间: ").append(report.getGeneratedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\n");
        sb.append("报告期间: ").append(report.getReportPeriodStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
          .append(" 至 ").append(report.getReportPeriodEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))).append("\n");
        sb.append("合规状态: ").append(report.getComplianceStatus()).append("\n");
        sb.append("合规评分: ").append(String.format("%.2f", report.getComplianceScore() * 100)).append("%\n\n");
        
        sb.append("执行摘要:\n");
        sb.append(report.getExecutiveSummary()).append("\n\n");
        
        // 章节内容
        for (ComplianceSection section : report.getSections()) {
            sb.append("-".repeat(60)).append("\n");
            sb.append(section.getSectionTitle()).append("\n");
            sb.append("-".repeat(60)).append("\n");
            sb.append(section.getContent()).append("\n");
            sb.append("状态: ").append(section.getStatus()).append("\n\n");
        }
        
        // 发现的问题
        if (!report.getFindings().isEmpty()) {
            sb.append("发现的问题:\n");
            sb.append("-".repeat(40)).append("\n");
            for (ComplianceFinding finding : report.getFindings()) {
                sb.append("类型: ").append(finding.getFindingType()).append("\n");
                sb.append("严重程度: ").append(finding.getSeverity()).append("\n");
                sb.append("描述: ").append(finding.getDescription()).append("\n");
                if (finding.getRecommendation() != null) {
                    sb.append("建议: ").append(finding.getRecommendation()).append("\n");
                }
                sb.append("\n");
            }
        }
        
        // 建议
        if (!report.getRecommendations().isEmpty()) {
            sb.append("改进建议:\n");
            sb.append("-".repeat(40)).append("\n");
            for (int i = 0; i < report.getRecommendations().size(); i++) {
                sb.append((i + 1)).append(". ").append(report.getRecommendations().get(i)).append("\n");
            }
        }
        
        return sb.toString();
    }
}